#include <os/sconfig.h>
#include <lib/string.h>
#include <lib/stdlib.h>
#include <lib/ctype.h>

#define SCONFIG_SEPARATOR_DEFAULT '@'

static char _separator = SCONFIG_SEPARATOR_DEFAULT;

int SConfigSetSeparator(char separator)
{
    _separator = separator;
}

char SConfigGetSeparator()
{
    return _separator;
}

int SConfigBool(const char *str)
{
    if (!str)
        return 0;
    if (!strncmp(str, "true", 4))
        return 1;
    return 0;
}

int SConfigInt(const char *str)
{
    if (!str)
        return 0;
    return atoi(str);
}

int SConfigWrite(char *line, const char *str)
{
    char s[2] = {_separator, '\0'};
    if (!line || !str)
        return -1;
    strcat(line, str);
    strcat(line, s);
}

char *SConfigRead(char *line, const char *str, int len)
{
    char *p = line, *s = (char *)str;
    int byte = len;

    if (!line || !str)
        return NULL;
    if (!*line)
        return NULL;
    while (*p)
    {
        if (*p == _separator)
        {
            p++;
            break;
        }
        if (len-- > 0)
        {
            *s++ = *p++;
        }
    }
    s = (char *)str;
    s[byte - len] = '\0';
    return p;
}

int SConfigWriteLine(char *line)
{
    char buff[] = {'\n', '\0'};
    if (!line)
        return -1;
    strcat(line, buff);
}

char *SConfigReadLine(char *buff, const char *line, int len)
{
    char *p = buff;
    char *q = (char *)line;
    int bytes = len;

    if (!buff || !line || len <= 0)
        return NULL;
    if (*buff == '\0')
        return NULL;
    while (*p)
    {
        if (*p == '\r') // '\r\n'
        {
            p++;
            if (*p == '\n') // '\n'
            {
                p++;
                break;
            }
            else //'\r'
                break;
        }
        if (*p == '\n') // '\r'
        {
            p++;
            break;
        }
        if (len > 0)
        {
            *q++ = *p;
            len--;
        }
        p++;
    }
    q = (char *)line;
    q[len - 1] = '\0';
    return p;
}

int SConfigTrim(char *str)
{
    char *start = str, *end;
    int len = strlen(str);

    start = str;
    end = str + len;
    if (!str)
        return -1;

    while (*start && isspace(*start))
        start++; // cut start space
    while (*end && isspace(*end))
        *end-- = '\0'; // cut end space use '\0' to full

    len = strlen(start);
    // copy to start of string
    strcpy(str, start);
    start = (char *)str;
    start[len] = '\0';
    return 0;
}
